import axios from 'axios';
import qs from 'qs';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/user/index.js';

const request = axios.create({
	baseURL: import.meta.env.VITE_BASE_URL,
	timeout: 15000,
	withCredentials: false,
	paramsSerializer: function (params) {
		return qs.stringify(params, { indices: false });
	}
});

//请求前拦截器
request.interceptors.request.use(function (config) {
	const userStore = useUserStore();
	config.headers['token'] = userStore.token;
	return config;
});

request.interceptors.response.use(function (response) {
	if (response.data.code !== 1) {
		//弹出错误信息
		ElMessage.error(response.data.msg);
		throw new Error(response.data.msg);
	}

	return response.data;
});

export default request;
